<template>
  <div class="container">
    <div class="serchHead">
      <el-row class="serchrow">
        <el-col :span="6" class="serchcol"
          ><span class="serchTitle">姓名&nbsp;</span>
          <el-input
            class="serchwidth"
            v-model="serchName"
            size="small"
            placeholder="请输入姓名"
        /></el-col>
        <el-col :span="6" class="serchcol"
          ><span class="serchTitle">手机号&nbsp;</span>
          <el-input
            class="serchwidth"
            v-model="serchTel"
            size="small"
            placeholder="请输入手机号"
        /></el-col>
        <el-col :span="6" class="serchcol">
          <span class="serchTitle">学校&nbsp;</span
          ><el-input
            class="serchwidth"
            v-model="serchSchool"
            size="small"
            placeholder="请输入学校"
        /></el-col>
        <el-col :span="6" class="serchcol"
          ><span class="serchTitle">学院&nbsp;</span>
          <el-input
            class="serchwidth"
            v-model="serchAcademy"
            size="small"
            placeholder="请输入学院"
        /></el-col>
      </el-row>
      <el-row class="serchrow serchrow1">
        <el-col :span="10" class="serchcol">
          <span class="serchTitle">创建时间&nbsp;</span>
          <el-date-picker
            style="width: 52%"
            v-model="serchCreatTime"
            type="daterange"
            size="small"
            start-placeholder="开始"
            end-placeholder="结束"
            :default-value="[new Date(2010, 9, 1), new Date(2010, 10, 1)]"
          />
          <span class="btns">
            <el-button type="primary" size="small" @click="filterData()"
              ><i class="el-icon-search"></i>搜索</el-button
            >
            <el-button size="small" @click="resetSerch()"
              ><i class="el-icon-refresh"></i>重置</el-button
            >
          </span>
        </el-col>
        <el-col :span="14"></el-col>
      </el-row>
    </div>
    <div>
      <div class="tableoperates">
        <div class="tabbtns">
          <!-- <el-button type="primary" plain size="small" @click="openAdd()"
            ><i class="el-icon-plus"></i>增加</el-button
          > -->
          <el-button type="primary" plain size="small" :disabled="authBtns" @click="openAuth()"
            ><i class="el-icon-star-on"></i>权限</el-button
          >
          <el-button
            type="success"
            plain
            size="small"
            :disabled="editBtns"
            @click="openEdit()"
            ><i class="el-icon-edit"></i>重置</el-button
          >
          <el-button
            type="danger"
            plain
            size="small"
            :disabled="deleBtns"
            @click="opendelete()"
            ><i class="el-icon-delete"></i>删除</el-button
          >
          <el-button type="info" plain size="small" @click="openImport()"
            ><i class="el-icon-upload2"></i>导入</el-button
          >
          <el-button type="warning" plain size="small" @click="openExport()"
            ><i class="el-icon-download"></i>导出</el-button
          >
        </div>
        <div class="icons">
          <i class="iicon"><el-icon><ZoomOut /></el-icon></i>
          <i class="iicon"><el-icon><Refresh /></el-icon></i>
          <i class="iicon"><el-icon><Grid /></el-icon></i>
        </div>
      </div>
      <div>
        <el-table
          ref="multipleTableRef"
          :data="showTableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="45" />
          <el-table-column label="权限" prop="role" align="center">
            <template #default="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag v-if="scope.row.role=='student'">{{ scope.row.role }}</el-tag>
                <el-tag type="success" v-else-if="scope.row.role=='teacher'">{{ scope.row.role }}</el-tag>
                <el-tag type="danger" v-else-if="scope.row.role=='admin'">{{ scope.row.role }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in standardTableColumn"
            :key="index"
            :label="item.label"
            :prop="item.prop"
            align="center"
          ></el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible1" title="编辑信息" width="30%">
      <el-form :model="user" ref="form1" :rules="rules">
        <el-row>
          <el-form-item
            label="学号"
            :label-width="formLabelWidth"
            prop="identityId"
          >
            <el-input
              v-model="user.identityId"
              autocomplete="off"
              disabled
              style="width: 219px"
            />
          </el-form-item>
          <el-form-item
            label="姓名"
            :label-width="formLabelWidth"
            prop="realName"
          >
            <el-input
              v-model="user.realName"
              autocomplete="off"
              disabled
              style="width: 219px"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="昵称"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input
              v-model="user.username"
              autocomplete="off"
              style="width: 219px"
            />
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-select v-model="user.gender" placeholder="男">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="学校"
            :label-width="formLabelWidth"
            prop="school"
          >
            <el-input
              v-model="user.school"
              autocomplete="off"
              style="width: 219px"
            />
          </el-form-item>
          <el-form-item
            label="学院"
            :label-width="formLabelWidth"
            prop="academy"
          >
            <el-input
              v-model="user.academy"
              autocomplete="off"
              style="width: 219px"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="权限" :label-width="formLabelWidth" prop="role">
            <el-select
              v-model="user.role"
              class="m-2"
              placeholder="Select"
              size="small"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancle()">取消</el-button>
          <el-button type="primary" @click="edit()">修改</el-button>
        </span>
      </template>
    </el-dialog>
    <div class="pagContainer">
      <div class="pagination">
        <el-pagination
          :hide-on-single-page="value"
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { getAllUsers, deleteById, resetPassword } from "@/api/manage";
import {update } from "../../api/user.js";

export default {
  name: "template1",
  components: {},
  data() {
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        // alert('请再次输入密码')
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form2.password) {
        // alert('两次输入密码不一致!')
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // tableData: [
      //   {
      //     id: "085274fc-d05c-4988-a2c0-b0822e8fc349",
      //     tel: "13393857915",
      //     password: "9e858b0adec70ed571ca9f17eb7301be",
      //     role: "student",
      //     identityId: "631907060502",
      //     username: "陈洋名的太阳",
      //     realName: "张洋名",
      //     gender: "女",
      //     birth: "2022-10-31T16:00:00.000Z",
      //     picture:
      //       "https://cqjtu-education.oss-cn-beijing.aliyuncs.com/course_cover/8599-2022-10-28 19:49:52-nav_icon_01.png",
      //     account: 0,
      //     integral: 0,
      //     email: "2049515545@qq.com",
      //     lastTime: 1667474712767,
      //     createTime: 1656989428000,
      //     school: "重庆交通大学",
      //     academy: "信息科学与工程学院",
      //   },
      //   {
      //     id: "085274fc-d05c-4988-a2c0-b0822e8fc349",
      //     tel: "15839180138",
      //     password: "9e858b0adec70ed571ca9f17eb7301be",
      //     role: "student",
      //     identityId: "631907060502",
      //     username: "陈洋名的太阳",
      //     realName: "张洋名",
      //     gender: "女",
      //     birth: "2022-10-31T16:00:00.000Z",
      //     picture:
      //       "https://cqjtu-education.oss-cn-beijing.aliyuncs.com/course_cover/8599-2022-10-28 19:49:52-nav_icon_01.png",
      //     account: 0,
      //     integral: 0,
      //     email: "2049515545@qq.com",
      //     lastTime: 1667474712767,
      //     createTime: 1656989428000,
      //     school: "重庆交通大学",
      //     academy: "信息科学与工程学院",
      //   },
      //   {
      //     id: "085274fc-d05c-4988-a2c0-b0822e8fc349",
      //     tel: "13393857915",
      //     password: "9e858b0adec70ed571ca9f17eb7301be",
      //     role: "student",
      //     identityId: "631907060502",
      //     username: "陈洋名的太阳",
      //     realName: "李洋名",
      //     gender: "女",
      //     birth: "2022-10-31T16:00:00.000Z",
      //     picture:
      //       "https://cqjtu-education.oss-cn-beijing.aliyuncs.com/course_cover/8599-2022-10-28 19:49:52-nav_icon_01.png",
      //     account: 0,
      //     integral: 0,
      //     email: "2049515545@qq.com",
      //     lastTime: 1667474712767,
      //     createTime: 1656989428000,
      //     school: "重庆交通大学",
      //     academy: "信息科学与工程学院",
      //   },
      //   {
      //     id: "085274fc-d05c-4988-a2c0-b0822e8fc349",
      //     tel: "13393857915",
      //     password: "9e858b0adec70ed571ca9f17eb7301be",
      //     role: "student",
      //     identityId: "631907060502",
      //     username: "陈洋名的太阳",
      //     realName: "王洋名",
      //     gender: "女",
      //     birth: "2022-10-31T16:00:00.000Z",
      //     picture:
      //       "https://cqjtu-education.oss-cn-beijing.aliyuncs.com/course_cover/8599-2022-10-28 19:49:52-nav_icon_01.png",
      //     account: 0,
      //     integral: 0,
      //     email: "2049515545@qq.com",
      //     lastTime: 1667474712767,
      //     createTime: 1656989428000,
      //     school: "重庆交通大学",
      //     academy: "信息科学与工程学院",
      //   },
      //   {
      //     id: "085274fc-d05c-4988-a2c0-b0822e8fc349",
      //     tel: "13393857915",
      //     password: "9e858b0adec70ed571ca9f17eb7301be",
      //     role: "student",
      //     identityId: "631907060502",
      //     username: "陈洋名的太阳",
      //     realName: "朱洋名",
      //     gender: "女",
      //     birth: "2022-10-31T16:00:00.000Z",
      //     picture:
      //       "https://cqjtu-education.oss-cn-beijing.aliyuncs.com/course_cover/8599-2022-10-28 19:49:52-nav_icon_01.png",
      //     account: 0,
      //     integral: 0,
      //     email: "2049515545@qq.com",
      //     lastTime: 1667474712767,
      //     createTime: 1656989428000,
      //     school: "重庆交通大学",
      //     academy: "信息科学与工程学院",
      //   },

      // ],
      tableData: [],
      tableColumn: [
        {
          label: "学号",
          prop: "identityId",
          visable: true,
        },
        {
          label: "姓名",
          prop: "realName",
          visable: true,
        },
        {
          label: "昵称",
          prop: "username",
          visable: true,
        },
        {
          label: "性别",
          prop: "gender",
          visable: true,
        },
        {
          label: "电话号",
          prop: "tel",
          visable: true,
        },
        {
          label: "学校",
          prop: "school",
          visable: true,
        },
        {
          label: "学院",
          prop: "academy",
          visable: true,
        },
        {
          label: "创建时间",
          prop: "createTime",
          visable: true,
        },
        {
          label: "上次登录",
          prop: "lastTime",
          visable: true,
        },
      ],
      showTableData: [],
      //搜索
      serchName: "",
      serchTel: "",
      serchSchool: "",
      serchAcademy: "",
      serchCreatTime: "",
      //选中
      multipleSelection: [],
      //按钮控制
      editBtns: true,
      authBtns: true,
      deleBtns: true,
      //分页
      background: true,
      value: true,
      total: 40,
      pageSize: 5,
      currentPage: 1,
      rules: {
        identityId: [{ required: true, message: "学号是必填项" }],
        username: [{ required: true, message: "昵称是必填项" }],
        realName: [{ required: true, message: "姓名是必填项" }],
        role: [{ required: true, message: "权限是必填项" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern:
              /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,30}$/,
            message:
              "密码为数字、小写字母、大写字母、特殊符号，至少包含三种，长度为8 - 30位",
          },
        ],
        repassword: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
        tel: [
          { required: true, message: "请输入电话号", trigger: "blur" },
          {
            pattern:
              /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: "请输入正确的手机号",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱号", trigger: "blur" },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "请输入正确的邮箱",
          },
        ],
        school: [{ required: true, message: "学校是必填项" }],
        academy: [{ required: true, message: "学院是必填项" }],
      },
      user: {},
      dialogFormVisible1: false,
      formLabelWidth: "140px",
      options: [
        {
          value: "admin",
          label: "管理员",
        },
        {
          value: "teacher",
          label: "老师",
        },
        {
          value: "student",
          label: "学生",
        },
      ],
    };
  },
  methods: {
    resetSerch() {
      this.serchName = "";
      this.serchTel = "";
      this.serchSchool = "";
      this.serchAcademy = "";
      this.serchCreatTime = "";
      this.filterData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    filterData() {
      this.showTableData = this.tableData
        .filter(
          (item) =>
            !this.serchName ||
            item.realName.toLowerCase().includes(this.serchName.toLowerCase())
        )
        .filter((item) => !this.serchTel || item.tel.includes(this.serchTel))
        .filter(
          (item) => !this.serchSchool || item.school.includes(this.serchSchool)
        )
        .filter(
          (item) =>
            !this.serchAcademy || item.academy.includes(this.serchAcademy)
        )
        .filter(
          (item) =>
            !this.serchCreatTime ||
            (new Date(item.createTime) >= this.serchCreatTime[0] &&
              new Date(item.createTime) <= this.serchCreatTime[1])
        );
    },
    openEdit() {
      let result = window.confirm("确定重置用户密码吗？");
      if (result) {
        resetPassword(
          this.multipleSelection[0].id,
          this.multipleSelection[0].tel.slice(5)
        ).then((res) => {
          if (res.code == 200) {
            ElMessage({
              type: "success",
              message: "重置成功",
            });
          } else {
            ElMessage({
              type: "error",
              message: "重置失败",
            });
          }
        });
      } else {
        ElMessage({
          type: "info",
          message: "已取消",
        });
      }
    },
    openAuth() {
      this.user = this.multipleSelection[0];
      this.dialogFormVisible1 = true;
    },
    opendelete() {
      let result= window.confirm('确定删除该用户？')
      if(result){
         deleteById(this.multipleSelection[0].id).then((res) => {
        if (res.code == 200) {
          this.multipleSelection.forEach((item) => {
            this.tableData.splice(this.tableData.indexOf(item), 1);
          });
          this.filterData();
          this.total--;
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "删除失败",
          });
        }
      });
      }else{
        ElMessage({
          type:'info',
          message:'已取消'
        })
      }
     
    },
    openImport() {
      alert("批量导入待完善！");
    },
    openExport() {
      alert("批量导出待完善！");
    },
    getTableData() {
      getAllUsers(this.currentPage, this.pageSize).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.filterData();
        } else {
          ElMessage({
            type: "error",
            message: "获取用户列表失败",
          });
        }
      });
    },
    edit() {
      this.$refs.form1.validate((val) => {
        console.log(val)
      if (val) {
          update(this.user).then((res) => {
            if (res.code == 200) {
              ElMessage({
                type: "success",
                message: "更新成功",
              });
              return '200'
            } else {
              ElMessage({
                type: "error",
                message: "信息更新失败",
              });
              return '-1'
            }
          }).then(res=>{
            if(res==200)
            {
              this.getTableData()
            }
          });
          this.dialogFormVisible1 = false;
        }
      });
    },
    cancle() {
      this.dialogFormVisible1 = false;
    },
    getTotal(){
      getAllUsers(1,100000).then(res=>{
        if(res.code==200)
        {
          this.total=res.data.length
        }else{
          ElMessage({
            type:'error',
            message:'获取总条数失败'
          })
        }
      })
    }
  },
  created() {
    this.getTotal()
    this.getTableData();
    
  },
  mounted() {},
  computed: {
    standardTableColumn() {
      return this.tableColumn.filter((item) => item.visable);
    },
  },
  watch: {
    multipleSelection: {
      handler(newVal) {
        if (newVal.length > 0) {
          if (newVal.length == 1) {
            this.deleBtns = false;
            this.editBtns = false;
            this.authBtns = false;
          } else {
            this.deleBtns = false;
            this.editBtns = true;
            this.authBtns = true;
          }
        } else {
          this.deleBtns = true;
          this.editBtns = true;
          this.authBtns = true;
        }
      },
      immediate: true,
    },
    pageSize: {
      handler(newVal) {
        this.getTableData();
      },
    },
    currentPage: {
      handler(newVal) {
        this.getTableData();
      },
    },
  },
};
</script>
<style scoped>
.container {
  height: 100%;
  margin-top: 10px;
}
.serchHead{
  margin-top:20px;
}
.serchTitle {
  line-height: 30px;
  font-weight: 600;
}
.serchwidth {
  width: 70%;
}
.serchrow {
  height: 30px;
}
.serchrow1 {
  margin-top: 15px;
}
.serchcol {
  height: 100%;
}
.btns {
  margin-left: 10px;
}
.tableoperates {
  margin-bottom: 15px;
  margin-top: 15px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 0px 10px;
}
.tabbtns {
  margin-left: 20px;
}
.icon {
  font-size: 20px;
  margin-left: 10px;
  cursor: pointer;
}
.pagContainer {
  display: flex;
  margin-top: 10px;
  align-items: center;
  justify-content: center;
}
.icons{
  display: flex;
  font-size: 18px;
  padding: 0 20px;
}
.iicon{
  margin-left: 10px;
}
</style>